# -*- coding: utf-8 -*-
from django.contrib import admin
from app.models import Statistic
from random import randint


def init_static_data():
    for i in range(20):
        stat = Statistic()
        stat.target_name = '开课直播'
        stat.start_time = i
        stat.end_time = i + 1
        stat.unit = 60
        stat.count = randint(1, 200)
        stat.save()
    for i in range(20):
        stat = Statistic()
        stat.target_name = '毕业典礼直播'
        stat.start_time = i
        stat.end_time = i + 1
        stat.unit = 60
        stat.count = randint(1, 200)
        stat.save()


class StatisticAdmin(admin.ModelAdmin):
    change_list_template = 'admin/statistic_test.html'

    def changelist_view(self, request, extra_context=None):
        response = admin.ModelAdmin.changelist_view(self, request, extra_context)

        name = request.POST.get('name')
        if not name:
            response.context_data['statistic_info'] = {
                'x_axis': [0],
                'data': [0],
                'title': '无'
            }
            return response
        qs = Statistic.objects.filter(target_name=name).order_by('target_name', 'start_time')
        count = qs.count()
        x_axis = ['开始']
        i = 0
        while True:
            i += 1
            x = '%d分钟' % (i * 2)
            if i * 2 > count:
                break
            x_axis.append(x)

        data = []
        i = 0
        for s in qs:
            if i % 2 == 0:
                data.append(s.count)
        response.context_data['statistic_info'] = {
            'x_axis': x_axis,
            'data': data,
            'title': name,
        }
        return response


admin.site.register(Statistic, StatisticAdmin)

if Statistic.objects.all().count() == 0:
    init_static_data()
